package xyxy.ymh;

import org.apache.catalina.LifecycleException;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.startup.Tomcat;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.Servlet;

public class TomcatWebServer implements WebServer{
    @Override
    public void start(WebApplicationContext webApplicationContext) {

        // 创建tomcat服务器
        Tomcat tomcatServer = new Tomcat();
        // 指定端口号
        tomcatServer.setPort(8081);
        // 是否设置自动部署
        tomcatServer.getHost().setAutoDeploy(false);
        // 创建上下文
        StandardContext standardContex = new StandardContext();
        String context="";
        standardContex.setPath(context);
        // 监听上下文
        standardContex.addLifecycleListener(new Tomcat.FixContextListener());
        // tomcat容器添加standardContex
        tomcatServer.getHost().addChild(standardContex);
        // 创建Servlet
        tomcatServer.addServlet(context,"dispatcherServlet", (Servlet) new DispatcherServlet(webApplicationContext));
        // servleturl映射
        standardContex.addServletMappingDecoded("/","dispatcherServlet");
        try {
            tomcatServer.start();
        } catch (LifecycleException e) {
            throw new RuntimeException(e);
        }
        System.out.println("tomcat start success..");
        // 异步进行接收请求
        tomcatServer.getServer().await();
    }
}
